package com.bite.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.constants.JwtConstants;
import com.bite.common.core.domain.R;
import com.bite.common.core.enums.LoginUserIdentity;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.redis.service.RedisService;
import com.bite.common.security.exception.ServiceException;
import com.bite.common.security.service.TokenService;
import com.bite.system.Domain.entity.SysUser;
import com.bite.system.mapper.SysUserMapper;
import com.bite.system.service.ISysUserService;
import com.bite.system.utils.BCryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    // nacos拉取
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    private RedisService redisService;

    @Override
    public R<String> login(String userAccount, String password) {
        // 通过账户去数据库中查询用户对应的信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();

        // select password user_id from tb_sys_user where user_account = #{userAccount};
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getPassword, SysUser::getUserId)
                .eq(SysUser::getUserAccount, userAccount));

        if (sysUser == null) {
            return R.fail(ResultCode.FAILED_LOGIN);
        } else if (BCryptUtil.matchesPassword(password, sysUser.getPassword())) {

            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtConstants.LOGIN_USER_ID, sysUser.getUserId());

            String token = tokenService.createTokenAndRedisDTS(claims, jwtSecret,
                    LoginUserIdentity.ADMIN);

            return R.ok(token);
        } else {
            return R.fail(ResultCode.FAILED_LOGIN);
        }
    }

    @Override
    public int add(String userAccount, String password) {
        // 网关已经做完了身份验证
        // 将用户添加到数据库中即可，注意检查用户是否已经存在

        // 0.检查用户是否存在
        boolean exists = sysUserMapper.selectCount(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, userAccount))
                > 0;
        if (exists) {
            // 直接抛异常
            throw new ServiceException(ResultCode.FAILED_USER_EXISTS);
        }

        // 1.添加用户
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(userAccount);
        sysUser.setPassword(BCryptUtil.encryptPassword(password));
        // createBy 跟 createTime使用MybatisPlus的自动填充字段功能
        return sysUserMapper.insert(sysUser);
    }

}
